package com.yanbing.service;

import com.spring.BeanNameAware;
import com.spring.BeanPostProcessor;
import com.spring.Component;
import com.spring.Scope;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


/**
 * @author yanbing
 * @version 1.0
 * @date 2021/9/4 21:16
 */
@Component
public class YanibngBeanPostProcessor implements BeanPostProcessor {

    public Object postProcessAfterInitialization(Object bean, String beanName) {
        //我们这里简单化了，AOP源码做了大量工作识别类的方法是否需要切面
        if ("orderService".equals(beanName)) {
            System.out.println("postProcessAfterInitialization  action ..............");
            //使用jdk动态代理生成代理类，AOP中大部分对象都是通过cglib生成代理对象
            Object proxy = Proxy.newProxyInstance(YanibngBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("aop 切面核心逻辑");
                    //此方法才是真实方法的执行
                    return method.invoke(bean, args);
                }
            });
            return proxy;
        }
        return bean;
    }

}
